package news

import (
	"beegoProject16/models/news"
	"beegoProject16/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"math"
	"strconv"
	"time"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) Get() {

	// 1. 数据库
	o := orm.NewOrm()
	qs := o.QueryTable("sys_news")

	// 2.
	newData := []news.News{}

	/*
	 --------------- 分页 ----------------
	*/
	// 每页显示数据-4条 (pagePerNum)
	pagePerNum := 5

	var count int64 = 0

	// 当前页 (currentPage)
	currentPage, err := c.GetInt("page")

	// err 当点击页面时候没有获取到当前页也就是null，所以默认显示第一页
	if err != nil {
		currentPage = 1
	}

	/*
		增加查询：
	*/
	offsetNum := pagePerNum * (currentPage - 1)

	kw := c.GetString("kw")

	/* 查询日志 */
	ret := fmt.Sprintf("当前页:%d,查询条件:%s", currentPage, kw)
	logs.Info(ret)

	if kw != "" { // 判断kw有查询条件的，那就会对总数和用户查询结果有影响
		// 总数据量--增加过滤username__contains
		count, _ = qs.Filter("is_delete", 0).Filter("title__contains", kw).Count()
		// 用户详细信息查询--增加过滤username__contains
		qs.Filter("is_delete", 0).Filter("title__contains", kw).Limit(pagePerNum).Offset(offsetNum).RelatedSel().All(&newData)
	} else {
		// 总数据量
		count, _ = qs.Filter("is_delete", 0).Count()
		// 详细查询增加表关联数据  .RelatedSel()
		qs.Filter("is_delete", 0).Limit(pagePerNum).Offset(offsetNum).RelatedSel().All(&newData)
	}

	// 总页数 (count) =  总数据量 / 每页数据量   注：需要转换成int类型
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))

	// 判断上一页
	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		// 上一页
		prePage = currentPage - 1
	}

	// 下一页
	nextPage := 1
	// 如果当前页小于总页数
	if currentPage < countPage {
		// 下一页 就等于 当前页+1
		nextPage = currentPage + 1
		// 如果当前页面大于等于总页数
	} else if currentPage >= countPage {
		// 下一页 就等于 当前页
		nextPage = currentPage
	}

	// 引用倒入到函数page.go
	pageMap := utils.Paginator(currentPage, pagePerNum, count)

	/*
	 --------------- 分页 ----------------
	*/

	c.Data["news"] = newData
	c.Data["prePage"] = prePage         /* 上一页*/
	c.Data["nextPage"] = nextPage       /* 下一页 */
	c.Data["currentPage"] = currentPage /* 当前页 */
	c.Data["countPage"] = countPage     /* 总页数 */
	c.Data["count"] = count
	c.Data["kw"] = kw
	c.Data["page_map"] = pageMap

	c.TplName = "news/news-list.html"
}

func (c *NewsController) ToAdd() {

	// 1 将数据库数据传到前端
	o := orm.NewOrm()
	qs := o.QueryTable("sys_category")
	categories := []news.Category{}
	qs.Filter("is_delete", 0).All(&categories)

	c.Data["categories"] = categories
	c.TplName = "news/news-add.html"
}

func (c *NewsController) DoAdd() {
	content := c.GetString("content")
	title := c.GetString("title")
	categoryId, _ := c.GetInt("category_id")
	isActive, _ := c.GetInt("is_active")

	o := orm.NewOrm()

	// 2 初始化Category对象
	category := news.Category{
		Id: categoryId,
	}

	// 1 初始化结构体对象赋值
	newsData := news.News{
		Title:    title,
		Content:  content,
		IsActive: isActive,
		Category: &category,
	}
	_, err := o.Insert(&newsData)

	// 3 前端返回对象
	messageMap := map[string]interface{}{}
	if err != nil {
		messageMap["code"] = 10001
		messageMap["msg"] = "数据插入错误"
	}
	messageMap["code"] = 200
	messageMap["msg"] = "数据插入成功"

	c.Data["json"] = messageMap
	c.ServeJSON()

}

func (c *NewsController) UpLoadImg() {
	// 1 获取前端文件
	file, fileHeader, err := c.GetFile("file")

	// 4 定义前端返回
	messageMap := map[string]interface{}{}

	// 2 关闭文件
	defer func() {
		file.Close()
	}()

	// 5 获取文件
	fileName := fileHeader.Filename

	// 6 按照日期定义时间戳
	timeUnixInt := time.Now().Unix()
	timeUnixStr := strconv.FormatInt(timeUnixInt, 10) // 10进制

	// 7 定义存储路径,创建路径 upload - news_img
	filePath := "upload/news_img/" + timeUnixStr + "_" + fileName

	// 8 路径拼接
	imgLink := "http://127.0.0.1:8080/" + filePath

	// 3 判断文件获取是否正航
	if err != nil {
		messageMap["code"] = 10001
		messageMap["msg"] = "文件上传失败"
		messageMap["link"] = imgLink
	}
	messageMap["code"] = 200
	messageMap["msg"] = "文件上传成功"
	messageMap["link"] = imgLink

	// 9 保存文件到存储路径
	c.SaveToFile("file", filePath)

	// 10
	c.Data["json"] = messageMap
	c.ServeJSON()

}

func (c *NewsController) ToEdit() {

	newsId, _ := c.GetInt("id")

	o := orm.NewOrm()
	qs := o.QueryTable("sys_news")

	// 查询当前登录到id
	newsData := news.News{}
	qs.Filter("id", newsId).RelatedSel().One(&newsData)

	categories := []news.Category{}

	// 除登录用户外其他用户
	o.QueryTable("sys_category").Exclude("id", newsData.Category.Id).All(&categories)

	c.Data["categories"] = categories
	c.Data["news_data"] = newsData
	c.TplName = "news/news-edit.html"
}

func (c *NewsController) DoEdit() {
	// 1.
	newsId, _ := c.GetInt("news_id")
	content := c.GetString("content")
	title := c.GetString("title")
	categoryId, _ := c.GetInt("category_id")
	isAcitve, _ := c.GetInt("is_active")

	// 2.
	o := orm.NewOrm()
	qs := o.QueryTable("sys_news")

	// 3.
	_, err := qs.Filter("id", newsId).Update(orm.Params{
		"title":       title,
		"content":     content,
		"category_id": categoryId,
		"is_active":   isAcitve,
	})

	// 5.
	messageMap := map[string]interface{}{}

	// 4.
	if err != nil {
		messageMap["code"] = 10001
		messageMap["msg"] = "更新失败"
	}
	messageMap["code"] = 200
	messageMap["msg"] = "更新成功"

	c.Data["json"] = messageMap
	c.ServeJSON()

}
